import { types, print, visit } from "recast";

const { identifier, variableDeclaration, variableDeclarator, returnStatement } =
  types.builders;

/**
 * 修改return语法，将返回表达式的语法，全部改为返回变量
 * @param {抽象语法树} ast
 */
const modifyReturn = (ast) => {
  visit(ast, {
    visitReturnStatement: function (path) {
      // 没有返回标识符，那么就将参数给一个标识符，然后再返回标识符
      if (
        path.node.argument !== null &&
        (path.node.argument.type !== "Identifier" &&
          path.node.argument.type !== "Literal")
      ) {
        const resultVar = variableDeclaration("const", [
          //将之前的const换成var来申明
          variableDeclarator(
            identifier(`result`), // name是之前在节点中获取到的申明的变量名称
            path.node.argument
          ),
        ]);
        const newReturn = returnStatement(identifier("result"));
        path.insertBefore(resultVar, newReturn);
        path.prune();
      }
      this.traverse(path);
    },
  });
};

export default modifyReturn;
